<template>
  <div class="container">
    <div class="app-container">
      <div class="role-operate">
        <el-button size="mini" type="primary" round @click="dialogVisible = true;isArr = true">添加角色</el-button>
      </div>
      <el-table
        :data="list"
        border
        style="width: 100%"
      >
        <!--  -->
        <el-table-column prop="name" align="center" label="角色" width="200">
          <template v-slot="{row}">
            <input v-if="row.isEdit" v-model="row.editRow.name" type="text">
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" label="启用" width="200">
          <template v-slot="{row}">
            <el-switch
              v-if="row.isEdit"
              v-model="row.editRow.state"
              active-color="#13ce66"
              :active-value="1"
              :inactive-value="0"
            />
            <span v-else>{{ row.state === 1 ? '已启用' : row.state === 0 ? '未启用' : '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" :rows="3" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="{row}">
            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="btnYes(row)">确认</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="bianji(row)">编辑</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="del(row.id)"
              >
                <el-button slot="reference" class="btn" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination
          layout="prev, pager, next"
          :current-page="pageParams.page"
          :page-size="pageParams.pagesize"
          :total="total"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <el-dialog
      :title="isArr? '新增角色':'编辑信息'"
      :visible.sync="dialogVisible"
      width="500px"
      @close="btnCancel"
    >
      <el-form ref="roleForm" label-width="120px" :model="addroles" :rules="addrules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="addroles.name" size="mini" />
        </el-form-item>
        <el-form-item label="启用" prop="state" size="mini">
          <el-switch
            v-model="addroles.state"
            active-color="#13ce66"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="addroles.description" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="btnCancel">取 消</el-button>
        <el-button type="primary" size="mini" @click="btnOK">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="分配权限"
      :visible.sync="showPermissionDialog"
      width="500px"
    >
      <el-tree
        ref="permTree"
        check-strictly
        node-key="id"
        :data="permissionData"
        :props="{label:'name'}"
        show-checkbox
        style="height:300px;overflow: auto;"
        :default-checked-keys="permIds"
      />
      <el-row slot="footer" type="flex" justify="center" align="center">
        <el-button type="primary" size="mini" @click="btnPermissionOK">确 定</el-button>
        <el-button size="mini" @click="showPermissionDialog = false">取 消</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getRoleList, addRole, updateRole, removRole, getRole, assignPrem } from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { zhuanghua } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      list: [],
      // 此状态用来判断当前点击的是添加还是编辑
      isArr: false,
      pageParams: {
        page: 1,
        pagesize: 5
      },
      total: 0,
      dialogVisible: false,
      // 绑定表单的数据
      addroles: {
        name: '',
        description: '',
        state: 0
      },
      // 校验规则
      addrules: {
        name: [{ required: true, message: '请输入角色名称' }],
        description: [{ required: true, message: '请输入对此角色的描述' }]
      },
      showPermissionDialog: false,
      permissionData: [], // 获取全部权限列表
      permIds: [] // 当前角色拥有的权限数组
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 渲染角色列表
    async getRoleList() {
      // 把需要的数据结构出来
      const { rows, total } = await getRoleList(this.pageParams)
      // 把结构的数据给到我的变量
      this.list = rows
      this.total = total

      this.list.forEach((item) => {
        // 为了复用弹出层 为，每一个数据添加一个区分编辑和添加的变量
        this.$set(item, 'isEdit', false)
        // 缓存变量，在添加和编辑的时候如果点取消不影响外层数据
        this.$set(item, 'editRow', {
          name: item.name,
          description: item.description,
          state: item.state
        })
      })
    },
    // 翻页
    changePage(newpage) {
      // console.log(newpage)
      // 更新当前页码，然后重新调用
      this.pageParams.page = newpage
      this.getRoleList()
    },
    btnOK() {
      // 获取表单实例校验表单
      this.$refs.roleForm.validate(async(isOk) => {
        // 表单校验成功isOK的值就是true反之亦然
        if (isOk) {
          // 判断当前点击的是添加还是编辑
          if (this.isArr) {
            await addRole(this.addroles)
            this.getRoleList()
            this.btnCancel()
          } else {
            await updateRole(this.addroles.id, this.addroles)
            this.getRoleList()
            this.btnCancel()
          }
        }
      })
    },
    btnCancel() {
      this.$refs.roleForm.resetFields()
      this.dialogVisible = false
    },
    async bianji(row) {
      // this.dialogVisible = true
      // row.isEdit = true
      row.isEdit = true
      row.editRow.name = row.name
      row.editRow.description = row.description
      row.editRow.state = row.state
      // const res = await getRole(row.id)
      // // this.isArr = false
      // this.addroles = res
    },
    async del(id) {
      await removRole(id)
      if (this.list.length === 1) this.pageParams.page--
      this.getRoleList()
    },
    async btnYes(row) {
      if (row.editRow.name && row.editRow.description) {
        await updateRole({ id: row.id, ...row.editRow })
        Object.assign(row, {
          ...row.editRow,
          isEdit: false
        }
        )
      } else {
        this.$message.warning('请输入角色和角色描述信息')
      }
    },
    async btnPermission(id) {
      this.currentRoleId = id
      this.permissionData = zhuanghua(await getPermissionList(), 0)
      const { permIds } = await getRole(id)
      this.permIds = permIds
      this.showPermissionDialog = true
    },
    async btnPermissionOK() {
      this.showPermissionDialog = false
      this.permIds = this.$refs.permTree.getCheckedKeys()
      await assignPrem({
        id: this.currentRoleId,
        permIds: this.permIds
      })
    }
  }
}
</script>
<style scoped>
.role-operate{
  padding: 10px;
}
.btn{
  margin-left: 10px;
}
</style>
